/*
 * MIT License
 *
 * Copyright (c) 2024-2025 milkpotatoes
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

#ifndef SRC_UTILS_INCLUDE_UTILS_H
#define SRC_UTILS_INCLUDE_UTILS_H

#include <functional>
#include <string>
#include <vector>

namespace utils
{
class StackCaller
{
public:
    explicit StackCaller(std::function<void(void)> func) : func_(func)
    {}
    ~StackCaller()
    {
        func_();
    }

private:
    std::function<void(void)> func_;
};

std::string GetRealPath(const char *path);
std::string GetCwd();
int ChDir(const char *path);

inline void Replace(std::string &str, const std::string &from, const std::string &to)
{
    size_t pos = 0;
    while ((pos = str.find(from, pos)) != std::string::npos)
    {
        str.replace(pos, from.length(), to);
        pos += to.length();
    }
}

inline void EscapeNull(std::string &str)
{
    if (str.size() == 0)
        return;
    for (size_t i = str.size() - 1; i >= 01; --i)
    {
        if (str[i] == '\0')
        {
            str.replace(i, 1, "\\0");
        }
    }
}

inline bool EndsWith(const std::string &string, const std::string &suffix)
{
    size_t stringLen = string.length();
    size_t suffixLen = suffix.length();

    if (suffixLen > stringLen)
    {
        return false;
    }
    return string.compare(stringLen - suffixLen, suffixLen, suffix) == 0;
}

bool IsStdOut();
bool IsStdErr();
std::string formatTimestamp(time_t timestamp);
} // namespace utils

#endif /* SRC_UTILS_INCLUDE_UTILS_H */